<template>
  <div class="sickness">
    <div class="sickness-page">
      <div class="sickness-page-box" style="padding-top: 60px">
        <div class="sickness-page-form">
          <el-input
            style="width: 300px"
            placeholder="请输入内容"
            v-model="formData.templateName"
          />
          <el-button
            type="primary"
            @click="addDepApi"
            v-if="selectedGroup.activeName_1 == '1'"
            >保存</el-button
          >
        </div>
        <div style="margin-top: 14px">
          <TagInput
            @add-tag="addTag"
            :recomScene="recomScene"
            :isNone="selectedGroup.activeName_1"
          />
        </div>
        <div style="margin-top: 14px;margin-bottom: 20px;">
          <outpatientTemplate
            ref="outpatientTemplateRef"
            :fieldList="fieldList"
            :activeName_1="selectedGroup.activeName_1"
            :dataType="selectedGroup.dataType"
            :doctorAdvice="formData.doctorAdvice"
          />
        </div>
        <div
          class="modal-footer relative"
          v-if="selectedGroup.activeName_1 == '1'"
        >
          <el-button
            style="float: right; "
            type="primary"
            @click="onAddTemplate"
            >确定</el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import TagInput from './TagInput.vue';
import outpatientTemplate from './outpatientTemplate.vue';
import { addTemplateMedical, updateTemplate } from '@/api/formwork';
import stores from '@/store';
const userBase = stores.useBaseDataStore();
interface TabItem {
  text: string;
  value: string;
}

const selectedGroup = defineProps<{
  selectedGroupId: any;
  templateMedicalDetail: any;
  dataType: string;
  activeName_1: string;
}>();
//console.log(selectedGroup.templateMedicalDetail);
const fieldList = ref<any[]>([]);
const recomScene = ref<string>('');
const formData = ref<any>({
  fieldList: [],
  templateName: '',
  templateType: '1',
  recomScene: '',
  groupId: selectedGroup.selectedGroupId,
  doctorAdvice: '',
});
watch(
  () => selectedGroup.templateMedicalDetail,
  (newVal) => {
    //console.log('templateMedicalDetail changed:', newVal);
    formData.value.templateName = newVal?.templateName || '';
    fieldList.value = newVal?.fieldList || [];
    recomScene.value = newVal?.recomScene || '';
    formData.value.recomScene = newVal.recomScene || '';
    formData.value.doctorAdvice = newVal.doctorAdvice || '';
  },
  { deep: true, immediate: true }
);
watch(
  () => selectedGroup,
  (newVal) => {
    //console.log(selectedGroup);
    if (newVal.dataType === '2') {
    } else {
      fieldList.value = [];
      formData.value.templateName = '';
      recomScene.value = '';
    }
    formData.value.templateType = newVal;
  },
  { immediate: true, deep: true }
);

const tabValue: TabItem[] = userBase.getEnumSelect('templateTypeEnum');
const emits = defineEmits(['refresh', 'updataTemplate']);
const outpatientTemplateRef = ref<any>();
const activeName = ref('1');
const addDepApi = async () => {
  //console.log(outpatientTemplateRef.value?.fields);
  formData.value.fieldList = outpatientTemplateRef.value?.fields.map(
    (item: any) => {
      return {
        fieldId: item.fieldId,
        fieldValue: item.content,
        fieldImages: Array.isArray(item.fieldImages)
          ? item.fieldImages
              .filter((v: any) => v !== null && v !== undefined && v !== '')
              .join(',')
          : item.fieldImages
          ? String(item.fieldImages)
          : '',
      };
    }
  );
  // formData.value.fieldList = medicalRecordFieldsRef.value?.fields.map(
  //   (item: any) => {
  //     return {
  //       fieldId: item.fieldId,
  //       fieldValue: item.content,
  //       fieldImages: item.fieldValue,
  //     };
  //   }
  // );

  if (selectedGroup.dataType === '2') {
    // 修改模板
    formData.value.templateId = selectedGroup.templateMedicalDetail?.templateId;
    formData.value.groupId = selectedGroup.selectedGroupId;
    formData.value.doctorAdvice = outpatientTemplateRef.value?.doctorAdvice1;
    // 更新模板
    updateTemplate(formData.value)
      .then((res) => {
        if (res.code !== '200') {
          return;
        }
        emits('refresh');
        ElMessage({
          type: 'success',
          message: res?.msg || '更新成功',
        });
      })
      .catch((error) => {
        //console.error('更新失败:', error);
      });
  } else {
    // 新增模板
    formData.value.groupId = selectedGroup.selectedGroupId;
    delete formData.value.templateId; // 确保新增时不包含templateId
    addTemplateMedical(formData.value)
      .then((res) => {
        if (res.code !== '200') {
          return;
        }
        emits('refresh');
        ElMessage({
          type: 'success',
          message: res?.msg || '添加成功',
        });
      })
      .catch((error) => {
        //console.error('添加失败:', error);
      });
  }
};
//选择模板
const onAddTemplate = () => {
  // templateDialog.value = true;
  emits('updataTemplate');
};
// 添加场景
const addTag = (tags: string[]) => {
  formData.value.recomScene = tags.join(',');
};
</script>

<style lang="scss" scoped>
.sickness {
  height: 100%;
}
.sickness-dialog {
  width: 80%;
  margin: 0 auto;
}
.sickness-page {
  background: #fff;
  border-radius: 6px;
  height: 100%;
  display: flex;
  .sickness-page-box {
    width: 100%;
    padding: 10px 20px;
    background: #ffffff;
    .sickness-page-form {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .sickness-page-form-right {
        margin-left: auto;
      }
    }
  }
  .sickness-page-nav {
    display: flex;
    align-items: center;
    justify-content: left;
    border-radius: 4px;
    border-bottom: 1px solid #e7e7e7;
    .el-dropdown-link {
      background: rgba(22, 173, 164, 0.08);
      border-radius: 0px 0px 0px 0px;
      padding: 16px 21px;
      cursor: pointer;
      color: var(--el-color-primary) !important;
      display: flex;
      font-size: 16px;
      align-items: center;
    }
  }
  .sickness-page-content {
    width: 288px;
    height: 100%;

    background: #f8f9fa;
    .sickness-page-form {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 10px 15px;
      border-bottom: 1px solid #e7e7e7;
      .sickness-page-form-right {
        margin-left: auto;
      }
    }
    .sickness-page-table {
      margin-top: 22px;
      height: calc(100% - 58px);
    }
    .sickness-page-pagination {
      margin-top: 24px;
      display: flex;
      align-items: center;
      .sickness-page-pagination-total {
        margin-right: auto;
        font-family: Microsoft YaHei, Microsoft YaHei;
        font-weight: 400;
        font-size: 14px;
        color: rgba(0, 0, 0, 0.6);
        text-align: left;
        font-style: normal;
        text-transform: none;
      }
    }
  }
}
</style>
<style lang="scss">
.sickness-tabs {
  .el-tabs__item {
    width: 60px !important; /* 设置每个tab的宽度 */
    padding: 0 !important; /* 去除默认padding */
  }
}
</style>
